%:- use_module(library(clpr)).
:- use_module(library('clp/bounds')).
%limit_stack(global,300000).

:- consult(conditions).
:- consult(inc_arr).

% path(N brigade, N from, N to, path time)
path(Br,0,B,T) :- 
	at(Br,AT), 
	ht(Br,B,HT), 
	T #= AT + HT.
%	write(0 -> B : T),nl.

path(Br,A,B,T) :- 
	ht(Br,A,HT1), 
	ht(Br,B,HT2), 
	T #= HT1 + HT2.
%	write(A -> B: T), nl.

% store path to list [A,B,T]
step(Br,A,B,T,[A,B,T]) :- path(Br,A,B,T).

route(_,X,X,0,[],HC,HC,0).

% route(N brigade, N from, N to, path time, Ps - edges list, HC - total quantity of patients delivered to each hospital before this route, HC - total quantity of patients delivered to each hospital after this route, Pq - number of patients)
% the path through points: X,Z,Y
route(Br,X,Y,T,Ps,HC,HCnew,Pq) :- %write('3333   '), nl,
		Pq #> 0, Pq1 #= Pq - 1,
		trim_stacks,
		route(Br,X,Z,T1,Ps1,HC,HC1,Pq1),
	%	trim_stacks,
		step(Br,Z,Y,T2,Ps2),
		inc(Y,_,HC1,HCnew),
		nth1(Y,HCnew,Hc1),
		hc(Y,Hc2),
		Hc1 =< Hc2,
		T #= T1 + T2,
		solution(BT,_,_),
		T < BT,
		Ps = [Ps1|Ps2].

%mutual(T - max time for all brigades, Ps - edges list of all brigades, HC - total quantity of patients delivered to each hospital, PQ - sum of patients)
%example: mutual(T,Ps,HC,2).
mutual(PQ):- [PQ1,PQ2] in 0..PQ,
		PQ1 + PQ2 #= PQ,
	%	solution(BT,_,_),
		HC1 = [0,0],
		route(1,0,_,T1,Ps1,HC1,HC2,PQ1),
	%	T1 < BT,
	%	trim_stacks,
		route(2,0,_,T2,Ps2,HC2,HC,PQ2),
		Ps = [Ps1, #|Ps2],
		T #= max(T1,T2),
	%	solution(BT,_,_),
	%	T < BT,
		retract(solution(_,_,_)),
		asserta(solution(T,Ps,HC)),
		fail.

% solve(TE - total time, PS - list of routs for brigades ([route of Br1 # rout of Br2]), HC - total quantity of patients delivered to each hospital, PQ - number of patients to save)
% example: solve(TE,PS,H,2).
solve(TE,PS,HC,PQ):- 
		asserta(solution(10000,ps,hc)),
		not(mutual(PQ)),
		retract(solution(TE,Ps,Hc)),
		flatten(Ps,PS),
		flatten(Hc,HC).


































